#include <QtGui>
#include "mainwindow.h"


MainWindow::MainWindow()
{
	setWindowTitle(tr("KPlazer"));
	createActions();
	
	readSettings();
	
	createTrayIcon();	
	trayIcon->show();
	
	
}

void MainWindow::closeEvent(QCloseEvent *event)
{
	writeSettings();
	event->accept();	
}

void MainWindow::setIcon(bool online)
{
	QIcon icon;
	
	if (online) {
		icon = QIcon(":/images/plazes.png");
	} else {
		icon = QIcon(":/images/offline.png");
	}
	
	trayIcon->setIcon(icon);
	setWindowIcon(icon);
	
}

void MainWindow::createTrayIcon()
{
	trayIconMenu = new QMenu(this);
	trayIconMenu->addAction(minimizeAction);
	trayIconMenu->addSeparator();
	trayIconMenu->addAction(restoreAction);
	trayIconMenu->addAction(quitAction);
	
	trayIcon = new QSystemTrayIcon(this);
	trayIcon->setContextMenu(trayIconMenu);
	trayIcon->setToolTip(tr("KPlazer.\nYou are here!"));
	setIcon(false);
	
	connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
		this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}

void MainWindow::createActions()
{
	minimizeAction = new QAction(tr("Mi&nimize"), this);
	minimizeAction->setShortcut(tr("Ctrl+N"));
	connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
		
	restoreAction = new QAction(tr("&Restore"), this);
	restoreAction->setShortcut(tr("Ctrl+R"));
	connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
	
	quitAction = new QAction(tr("&Quit"), this);
	quitAction->setIcon(QIcon(":/images/exit.png"));
	quitAction->setShortcut(tr("Ctrl+Q"));
	quitAction->setStatusTip(tr("Exit KPlazer"));
	connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
	
}


void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
	
	switch (reason) {
		case QSystemTrayIcon::Trigger:
			if (isHidden() == true) {
				show();
			} else {
				hide();
			}
			
		case QSystemTrayIcon::DoubleClick:
		case QSystemTrayIcon::MiddleClick:
		default:
			break;
	}
	
}

void MainWindow::writeSettings()
{
	QSettings settings("kplazer", "kplazer");
	settings.setValue("pos", pos());
	settings.setValue("size", size());
}

void MainWindow::readSettings()
{
	QSettings settings("kplazer", "kplazer");
	QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
	QSize size = settings.value("size", QSize(400, 400)).toSize();
	resize(size);
	move(pos);
}



